package com.wizz.trade.util;

import com.wizz.trade.common.ServiceException;
import com.wizz.trade.common.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * @author fyftless
 */
@Slf4j
@Component
public class FileOperationUtil {

    @Resource
    private FileStorageService fileStorageService;

    public String uploadImage(MultipartFile multipartFile) {
        // 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0){
            throw new ServiceException("文件为空");
        }

        // 生成文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String urlPath = null;
        try {
            urlPath = fileStorageService.uploadImgFile("", suffix, fileName, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，urlPath:{}",urlPath);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传图片失败");
        }

        // 返回文件路径
        return urlPath;
    }
}
